package com.dg11185.nearshop.net;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;

import com.dg11185.libs.network.NetClient;
import com.dg11185.libs.network.http.AsyncHttpResponseHandler;
import com.dg11185.libs.network.http.RequestParams;
import com.dg11185.libs.utils.netstate.NetWorkUtils;
import com.dg11185.nearshop.net.response.NetStatus;

/**
 * 接口缓存类，读取缓存数据和缓存接口数据
 * 
 * @author：Daibo
 * @time：2014-6-11 上午10:39:20
 */
public class NetCacheClient extends NetClient {

    /**
     * 当无网络连接或者缓存数据有效时读取缓存数据、否者读取网络数据
     */
    public static void httpCacheGet(HttpCacheRequest<?> request) {
        httpCacheGet(null, request);
    }

    /**
     * 1、如果Activity关闭后Http才回调并且调用关闭Activity参数会报空指针错误，这时候需要在
     * {@link Activity #onDestroy()方法中取消当前Activity的Http连接}
     * 
     * 2、传入context参数，在Activity关闭的时候可以通过
     * {@link NetClient #httpCancel(Context, boolean)}方法取消当前HTTP连接，
     */
    public static void httpCacheGet(Context mContext, HttpCacheRequest<?> request) {
        String fileName = request.getParams().get("chshSign");
        if (request.getIsCreateFloder()) {
            fileName = request.getMethod() + "/" + fileName;
        }
        FileCacheHelper helper = new FileCacheHelper(fileName);

        if (helper.isFileExist()) {
            switch (NetWorkUtils.getNetType()) {
            case NONE:
                request.onSuccess(helper.getFileString());
                System.out.println(request.getMethod() + ": no net valid");
                break;
            case WIFI:
                if (helper.isFileValid(request.getWifiTimeSpan())) {
                    request.onSuccess(helper.getFileString());
                    System.out.println(request.getMethod() + ": wifi valid");
                } else {
                    getNetData(mContext, request, helper);
                }
                break;
            default:
                if (helper.isFileValid(request.get_3GTimeSpan())) {
                    request.onSuccess(helper.getFileString());
                    System.out.println(request.getMethod() + ": 3g valid");
                } else {
                    getNetData(mContext, request, helper);
                }
                break;
            }
        } else {
            if (!NetWorkUtils.isNetConnected()) {
                System.out.println(request.getMethod() + ": no net && no cache");
                request.onFailure(NET_DISCONNECT_CODE);
            } else {
                getNetData(mContext, request, helper);
            }
        }
    }

    /**
     * 这个方法对返回数据格式有一定要求，必须是JSON格式且包含一个“status”的状态码， 只有成功时才保存到缓存
     * 它的可复用性差，不同的项目需要根据实际情况修改后才能使用
     */
    private static void getNetData(Context mContext, final HttpCacheRequest<?> request, final FileCacheHelper helper) {
        client.get(mContext, request.getUrl(), new RequestParams(request.getParams()), new AsyncHttpResponseHandler() {

            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                System.out.println("From net: ");
                String response = new String(responseBody);
                JSONObject object;
                try {
                    object = new JSONObject(response);
                    NetStatus status = NetStatus.getStatus(object.optString("status"));
                    if (NetStatus.SUCCESS == status) {
                        helper.writeToFile(response);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                request.onSuccess(response);
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
                request.onFailure(statusCode);
            }
        });
    }
}
